package org.afs.gescol.edt.api.dao.implementation;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.afs.gescol.edt.api.dao.interfaces.TimeSlotDao;
import org.afs.gescol.edt.api.dto.TimeSlotCriteria;
import org.afs.gescol.edt.api.model.TimeSlot;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.scub.foundation.framework.core.dao.implementations.HibernateDaoBaseImplementation;

/**
 * TimeSlotDao implementation.
 * @author Kobla GBENYO (kobla.gbenyo@gmail.com)
 */
public class TimeSlotDaoImpl extends HibernateDaoBaseImplementation implements TimeSlotDao {

    @Override
    public TimeSlot getTimeSlotById(Long id) {
        return load(id, TimeSlot.class);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<TimeSlot> getTimeSlotByCriteria(TimeSlotCriteria searchCriteria) {
        final Criteria criteria = createCriteria(TimeSlot.class);
        if (searchCriteria.getBeginDate() != null) {
            criteria.add(Restrictions.eq("beginDate", getCalendarFromDate(searchCriteria.getBeginDate())));
        }
        if (searchCriteria.getEndDate() != null) {
            criteria.add(Restrictions.eq("endDate", getCalendarFromDate(searchCriteria.getEndDate())));
        }
        if (searchCriteria.getSubject() != null && searchCriteria.getSubject().getId() != null) {
            criteria.add(Restrictions.eq("subjectEid", searchCriteria.getSubject().getId().toString()));
        }
        if (searchCriteria.getEntity() != null && searchCriteria.getEntity().getId() != null) {
            criteria.add(Restrictions.eq("entityEid", searchCriteria.getEntity().getId().toString()));
        }
        if (searchCriteria.getLeader() != null && searchCriteria.getLeader().getId() != null) {
            criteria.add(Restrictions.eq("leaderEid", searchCriteria.getLeader().getId().toString()));
        }
        return criteria.list();
    }

    @Override
    public void createTimeSlot(TimeSlot timeSlot) {
        save(timeSlot);
    }

    @Override
    public void deleteTimeSlot(TimeSlot timeSlot) {
        delete(timeSlot);
    }

    @Override
    public void cleanTimeSlot() {
        final Query query = createQuery("DELETE FROM TimeSlot");
        query.executeUpdate();
    }

    private Calendar getCalendarFromDate(Date date) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }
}
